package com.coalmine.api.controller;

import com.coalmine.api.domain.ApiDatasource;
import com.coalmine.api.domain.DataTypeDict;
import com.coalmine.api.domain.req.ListHistoryDataReqVO;
import com.coalmine.api.domain.resp.ApiDataDictSubTypeVO;
import com.coalmine.api.domain.resp.ApiDataDictVO;
import com.coalmine.api.domain.resp.ApiHistoryDataDictRespVO;
import com.coalmine.api.domain.resp.ListHistoryDataRespVO;
import com.coalmine.api.service.impl.ApiDatasourceServiceImpl;
import com.coalmine.api.service.impl.ApiHistoryDataServiceImpl;
import com.coalmine.common.core.domain.AjaxResult;
import com.coalmine.common.utils.StringUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@Api(value="历史数据管理API",tags={"API数据源表管理接口"})
@RequestMapping("/api/data/history")
public class ApiHistoryDataController {

    @Autowired
    private ApiDatasourceServiceImpl datasourceService;

    @Autowired
    private ApiHistoryDataServiceImpl historyDataService;

    @PreAuthorize("@ss.hasPermi('data:history:dict')")
    @GetMapping("/dict")
    public AjaxResult getDictInfo() {
        List<DataTypeDict> dicts = historyDataService.getDict();
        return AjaxResult.success(convert(dicts));
    }

    @PreAuthorize("@ss.hasPermi('data:history:list')")
    @PostMapping("/list")
    public AjaxResult list(@Validated @RequestBody ListHistoryDataReqVO reqVO) throws Exception {

        ApiDatasource datasource = datasourceService.getById(reqVO.getDatasourceId());
        if (StringUtils.isNull(datasource)) {
            return AjaxResult.error("数据源不存在！");
        }

        Object header = historyDataService.getHeader(datasource, reqVO.getTableName());
        long total = historyDataService.getTotal(datasource, reqVO.getTableName());
        if (total == 0) {
            return AjaxResult.success(new ListHistoryDataRespVO(header, null, total));
        }
        Object rows = historyDataService.getRows(datasource, reqVO.getTableName(),
                reqVO.getPageNum(), reqVO.getPageSize());
        return AjaxResult.success(new ListHistoryDataRespVO(header, rows, total));
    }

    private List<ApiHistoryDataDictRespVO> convert(List<DataTypeDict> dicts) {
        List<ApiHistoryDataDictRespVO> data = new ArrayList<>();

        Map<String, List<DataTypeDict>> typeMap = dicts.stream()
                .collect(Collectors.groupingBy(DataTypeDict::getTypeName));
        for (String type: typeMap.keySet()) {
            List<ApiDataDictSubTypeVO> subTypeVOList = new ArrayList<>();

            Map<String, List<DataTypeDict>> subTypeMap = typeMap.get(type).stream()
                    .collect(Collectors.groupingBy(DataTypeDict::getSubTypeName));
            for (String subType: subTypeMap.keySet()) {
                List<ApiDataDictVO> dictVOList = new ArrayList<>();

                List<DataTypeDict> dictList = subTypeMap.get(subType);
                for (DataTypeDict dict: dictList) {
                    dictVOList.add(new ApiDataDictVO(dict.getTableName(), dict.getTableComment(), dict.getDatasourceId()));
                }
                subTypeVOList.add(new ApiDataDictSubTypeVO(subType, subType, dictVOList));
            }
            data.add(new ApiHistoryDataDictRespVO(type, type, subTypeVOList));
        }
        return data;
    }
}
